﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.JCI.Common.Entity;
using Microsoft.JCI.Bll;
using System.Collections.Generic;
using Microsoft.JCI.Common.Utility;
using System.Text;

namespace Microsoft.JCI.Portal.Agent
{
    public partial class WorkItemAdd : BasePage
    {
        public Guid DispatchFormID
        {
            get
            {
                if (string.IsNullOrEmpty(txtDispatchFormID.Value)) return Guid.Empty;
                else return new Guid(txtDispatchFormID.Value);
            }
            set
            {
                txtDispatchFormID.Value = value.ToString();
            }
        }

        public Guid WorkingVendorOrderID
        {
            get
            {
                if (string.IsNullOrEmpty(txtWorkingVendorOrderId.Value)) return Guid.Empty;
                else return new Guid(txtWorkingVendorOrderId.Value);
            }
            set
            {
                txtWorkingVendorOrderId.Value = value.ToString();
            }
        }

        public Guid CustomerID
        {
            get
            {
                if (string.IsNullOrEmpty(txtCustomerID.Value)) return Guid.Empty;
                else return new Guid(txtCustomerID.Value);
            }
            set
            {
                txtCustomerID.Value = value.ToString();
            }
        }

        public Guid WorkingVendorOrderOtherItemId
        {
            get
            {
                if (string.IsNullOrEmpty(txtWorkingVendorOrderOtherItemId.Value)) return Guid.Empty;
                else return new Guid(txtWorkingVendorOrderOtherItemId.Value);
            }
            set
            {
                txtWorkingVendorOrderOtherItemId.Value = value.ToString();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitPage();

                if (Request.QueryString["DispatchFormID"] != null)
                {
                    DispatchFormID = new Guid(Request.QueryString["DispatchFormID"]);
                    LoadData();                   
                }

                if (Request.QueryString["WorkOrderID"] != null)
                {
                    WorkingVendorOrderID = new Guid(Request.QueryString["WorkOrderID"]);                   
                    GetEngineerLogs(true); 
                    DisWorkingVendorItemEntity ItemEntity = new DisWorkingVendorItemBll().Get<DisWorkingVendorItemEntity>(" and WorkingVendorOrderId = '" + WorkingVendorOrderID.ToString() + "'");
                    WorkingVendorOrderOtherItemId = ItemEntity.WorkingVendorOrderOtherItemId;
                    txtJobOrderNo.Text=ItemEntity.JobOrderNo;
                    txtUnitModel.Text = ItemEntity.UnitModel;
                    txtFactorySerialNo.Text = ItemEntity.FactorySerialNo;
                    txtCompressorSerialNo.Text = ItemEntity.CompressorSerialNo;
                    txtOilType.Text = ItemEntity.OilType;                   
                    if (ItemEntity.Property != null) {
                        string[] propertys = ItemEntity.Property.Split(new char[] { ',' });
                        foreach (ListItem item in cblProperty.Items)
                        {
                            foreach (string str in propertys) {
                                if (str == item.Value) {
                                    item.Selected = true;
                                }
                            }
                        }
                    }
                    txtFaultDescription.Text = ItemEntity.FaultDescription;
                    txtResolvingAction.Text = ItemEntity.ResolvingAction;
                    ddlServiceStatus.SelectedValue = ItemEntity.ServiceStatus;
                    txtFaultCode.Text = ItemEntity.FaultCode;               
                    if (ItemEntity.PartProperty != null)
                    {
                        string[] propertys = ItemEntity.PartProperty.Split(new char[] { ',' });
                        foreach (ListItem item in cblPartProperty.Items)
                        {
                            foreach (string str in propertys)
                            {
                                if (str == item.Value)
                                {
                                    item.Selected = true;
                                }
                            }
                        }
                    }
                    ddlWarrantyClain.SelectedValue = ItemEntity.WarrantyClain;
                    txtApprovedByOfficer.Text =  ItemEntity.ApprovedByOfficer;
                    txtApprovedByFty.Text = ItemEntity.ApprovedByFty;                 
                    txtLabor.Value = System.Convert.ToDouble(ItemEntity.Labor);               
                    txtLodging.Value = System.Convert.ToDouble(ItemEntity.Lodging);                                     
                    txtMisc.Value = System.Convert.ToDouble(ItemEntity.Misc);                
                    txtTransportation.Value = System.Convert.ToDouble(ItemEntity.Transportation);                    
                    txtMaterial.Value = System.Convert.ToDouble(ItemEntity.Material);                                                                                              
                }
            }
        }

        private void InitPage()
        {
            SystemBll bll = new SystemBll();
            List<SysDictionaryEntity> list = bll.GetDictionaryListFromCache(Microsoft.JCI.Common.Utility.Enumerator.DictionaryType.WorkFormProperty);
            cblProperty.DataSource = list;
            cblProperty.DataTextField = "ValueCN";
            cblProperty.DataValueField = "Code";
            cblProperty.DataBind();

        }

        private void LoadData()
        {
            if (DispatchFormID == Guid.Empty) return;

            DispatchBll bll = new DispatchBll();
            DisDispatchFormEntity entity = bll.Get<DisDispatchFormEntity>(DispatchFormID);
            if (entity != null)
            {
                if (entity.CustomerId != Guid.Empty)
                {
                    ucCustomerCtrlInfo.CustomerID = entity.CustomerId;
                    ucCustomerCtrlInfo.Enabled = false;

                    CustomerID = entity.CustomerId;
                }
            }

           
        }

        protected void lnkbtnSave_Click(object sender, EventArgs e)
        {
            Save();
            ClientScript.RegisterStartupScript(this.GetType(), "saveandnew", "alert('保存成功');", true);
        }

        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            Save();
            ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
        }

        private void Save()
        {
            DispatchBll bll = new DispatchBll();

            MadCustomerEntity CustomerEntity = ucCustomerCtrlInfo.CustomerEntity;
            CustomerEntity.CustomerId = CustomerID;

            DisWorkingVendorOrderEntity OrderEntity = new DisWorkingVendorOrderEntity();
            if (WorkingVendorOrderID != Guid.Empty)
            {
                OrderEntity.WorkingVendorOrderId = WorkingVendorOrderID;
            }
            else
            {
                OrderEntity.WorkingVendorOrderId = Guid.NewGuid();
            }
            WorkingVendorOrderID = OrderEntity.WorkingVendorOrderId;
            OrderEntity.DispatchFormId = DispatchFormID;
            OrderEntity.CustomerId = CustomerID;
            OrderEntity.ProductId = Guid.Empty;
            OrderEntity.WorkingType = (int)Enumerator.WorkType.Maintenance;
            OrderEntity.CreateOn = DateTime.Now;
            OrderEntity.CreateBy = base.CurrentUserEntity.Account;
            OrderEntity.IsChecked = false;

            DisWorkingVendorItemEntity ItemEntity = new DisWorkingVendorItemEntity();
            if (WorkingVendorOrderOtherItemId != Guid.Empty)
            {
                ItemEntity.WorkingVendorOrderOtherItemId = WorkingVendorOrderOtherItemId;
            }
            else
            {
                ItemEntity.WorkingVendorOrderOtherItemId = Guid.NewGuid();
            }
            ItemEntity.WorkingVendorOrderId = OrderEntity.WorkingVendorOrderId;
            ItemEntity.JobOrderNo = txtJobOrderNo.Text;
            ItemEntity.UnitModel = txtUnitModel.Text;
            ItemEntity.FactorySerialNo = txtFactorySerialNo.Text;
            ItemEntity.CompressorSerialNo = txtCompressorSerialNo.Text;
            ItemEntity.OilType = txtOilType.Text;

            StringBuilder sb = new StringBuilder();
            foreach (ListItem item in cblProperty.Items)
            {
                if (item.Selected)
                {
                    if (sb.Length != 0) sb.Append(",");
                    sb.Append(item.Value);
                }
            }
            ItemEntity.Property = sb.ToString();
            ItemEntity.FaultDescription = txtFaultDescription.Text;
            ItemEntity.ResolvingAction = txtResolvingAction.Text;
            ItemEntity.ServiceStatus = ddlServiceStatus.SelectedValue;
            ItemEntity.FaultCode = txtFaultCode.Text;
            sb = new StringBuilder();
            foreach (ListItem item in cblPartProperty.Items)
            {
                if (item.Selected)
                {
                    if (sb.Length != 0) sb.Append(",");
                    sb.Append(item.Value);
                }
            }
            ItemEntity.PartProperty = sb.ToString();
            ItemEntity.WarrantyClain = ddlWarrantyClain.SelectedValue;
            ItemEntity.ApprovedByOfficer = txtApprovedByOfficer.Text;
            ItemEntity.ApprovedByFty = txtApprovedByFty.Text;
            if(txtLabor.Value.HasValue)
                ItemEntity.Labor = (decimal)txtLabor.Value;
            if (txtLodging.Value.HasValue)
                ItemEntity.Lodging = (decimal)txtLodging.Value.Value;
            if (txtMisc.Value.HasValue)
                ItemEntity.Misc = (decimal)txtMisc.Value.Value;

            if (txtTransportation.Value.HasValue)
                ItemEntity.Transportation = (decimal)txtTransportation.Value.Value;
            if (txtMaterial.Value.HasValue)
                ItemEntity.Material = (decimal)txtMaterial.Value.Value;

            bll.SaveNewWorkingOrder(OrderEntity, ItemEntity, CustomerEntity);
 
            WorkingVendorOrderID = OrderEntity.WorkingVendorOrderId;

            DisDispatchFormEntity disFormEntity = bll.Get<DisDispatchFormEntity>(this.DispatchFormID);
            disFormEntity.IsOnsite = true;
            bll.InsertOrUpdate(disFormEntity);
        }


        #region 零件

        private void GetWorkingVenderParts(bool IsNeedDataBind)
        {
            DispatchBll bll = new DispatchBll();
            List<DisWorkingVenderPartsEntity> list = bll.GetAll<DisWorkingVenderPartsEntity>(" and WorkingVendorOrderId='" + WorkingVendorOrderID + "'");
                radGridWorkingVenderParts.DataSource = list;

                if (IsNeedDataBind)
            {
                radGridWorkingVenderParts.DataBind();
            }
        }

        protected void radGridWorkingVenderParts_ItemCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "delete")
            {
                DispatchBll bll = new DispatchBll();

                bll.Delete<DisWorkingVenderPartsEntity>(" and WorkingVenderPartsId='" + e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["WorkingVenderPartsId"].ToString()+"'");
            }
        }

        protected void radGridWorkingVenderParts_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e)
        {
            GetWorkingVenderParts(false);
        }

        protected void btnRefershParts_Click(object sender, EventArgs e)
        {
            GetWorkingVenderParts(true);
        }

        #endregion
        
        #region 工程师LOG

        protected void radGridEngineerLogs_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e)
        {
            GetEngineerLogs(false);
        }

        private void GetEngineerLogs(bool IsNeedDataBind)
        {
            DispatchBll bll = new DispatchBll();
            List<DisWorkingVendorEngineerEntity> list = bll.GetAll<DisWorkingVendorEngineerEntity>(" and WorkingVendorOrderId='" + WorkingVendorOrderID + "'");
            radGridEngineerLogs.DataSource = list;

            if (IsNeedDataBind)
            {
                radGridEngineerLogs.DataBind();
            }
        }

        protected void btnRefershLogs_Click(object sender, EventArgs e)
        {
            GetEngineerLogs(true);
        }
        #endregion

        protected void radGridEngineerLogs_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {
            if (e.Item.ItemType == Telerik.WebControls.GridItemType.Item || e.Item.ItemType == Telerik.WebControls.GridItemType.AlternatingItem)
            { 
                LinkButton lnkbtnEditLog = e.Item.FindControl("lnkbtnEditLog") as LinkButton;
                DisWorkingVendorEngineerEntity dv = e.Item.DataItem as DisWorkingVendorEngineerEntity;
                lnkbtnEditLog.Attributes.Add("onclick", "window.radopen(\"LogAdd.aspx?WorkingVendorEngineer=" + dv.WorkingVendorEngineer + "\" , \"LogAdd\");return false;");
            
            }
        }
    }
}
